package web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import objects.Board;
import objects.Player;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class RetireServlet
 */
@WebServlet(name = "Retire", urlPatterns =
{
    "/Retire"
})
public class RetireServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RetireServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// Set the content to be JSON, as it is a very easy way to pass several parameters in JS.
				// Every consequence the user might run into in the code is labeled in a specific code
				// so the web UI will react accordingly. (the "res" parameter of the json)
				response.setContentType("application/json");
			    response.setCharacterEncoding("UTF-8");
				
		String retiredPlayerName = request.getParameter("retiredPlayer");
			    
		Player retiredPlayer = Board.getInstance().getPlayerByName(retiredPlayerName);
		retiredPlayer.setInTheGame(false);
		retiredPlayer.setReason("retired");
		boolean onePlayerLeft = Board.getInstance().onePlayerLeft();
		
		if (Board.getInstance().getNumberOfHumansInGame() == 0)
		{
			onePlayerLeft = true;
		}
		
		JsonObject jsAction = new JsonObject();
		jsAction.addProperty("code", "retire");
		jsAction.addProperty("player", retiredPlayerName);
		jsAction.addProperty("message", "Player " +retiredPlayerName+ " has retired");
		jsAction.addProperty("hasMorePlayers", !onePlayerLeft);
		Board.getInstance().addJsActions(jsAction);
		
		if (Board.getInstance().getCurrPlayerInstance().getPlayerName().equals(retiredPlayerName))
		{
			EndTurnServlet.turnEnder();
		}
	}
	 
	@SuppressWarnings("unused")
	private class resultJson
	{
		boolean hasMorePlayers;
	}
}
